package com.gcgo.client;

import com.gcgo.serial.RpcRequest;
import com.gcgo.zk.ServiceDiscovery;

import java.lang.reflect.Proxy;
import java.util.UUID;

public class RpcConsumer {
    private Client client = null;
    ServiceDiscovery serviceDiscovery = new ServiceDiscovery("149.248.4.119:2182");

    //1.创建代理对象
    //providerName:UserService#sayHello#
    public Object createProxy(Class<?> serviceClass, String providerName) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass}, (proxy, method, args) -> {
                    //设置参数
                    //启动类传递的是字符串："UserService#sayHello#"
                    //现在封装成RpcRequest
                    RpcRequest rpcRequest = new RpcRequest();
                    rpcRequest.setClassName(serviceClass.getName());
                    String[] split = providerName.split("#");
                    rpcRequest.setMethodName(split[1]);
                    rpcRequest.setParameters(args);
                    Class<?>[] parameterTypes = new Class[args.length];
                    for (int i = 0; i < args.length; i++) {
                        parameterTypes[i] = args[i].getClass();
                    }
                    rpcRequest.setParameterTypes(parameterTypes);
                    //随机设置了一个ID，暂时没用
                    rpcRequest.setRequestId(UUID.randomUUID().toString());
                    //设置到userClientHandler中
                    //调用初始化netty客户端方法
                    //Client client = new Client("127.0.0.1",9998);
                    //Client client = null;
                    //ServiceDiscovery serviceDiscovery = new ServiceDiscovery("149.248.4.119:2182");
                    String serverAddress = serviceDiscovery.discover();//127.0.0.1:9998
                    if (serverAddress != null) {
                        String[] array = serverAddress.split(":");
                        if (array.length == 3) {//c00000001:127.0.0.1:9998
                            String host = array[1];
                            int port = Integer.parseInt(array[2]);
                            client = new Client(host, port);
                            //存入选择的服务节点名称
                            client.setNode(array[0]);
                        }
                    }
                    //将当前时间设置进去
                    rpcRequest.setRequestTime(System.currentTimeMillis());
                    //去服务端请求结果
                    assert client != null;
                    return client.send(rpcRequest);
                });
    }

}
